﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Halcon二次开发.Tools
{
    internal class HelpJsons
    {
        /// <summary>
        /// Json文件写入，可以自己选择路径
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="path"></param>
        public static void Write<T>(List<T> list, string path)
        {
            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                DataContractJsonSerializer data = new DataContractJsonSerializer(typeof(List<T>));

                data.WriteObject(file, list);
            }
        }
        public static void Write(Dictionary<string, string> list, string path)
        {
            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                DataContractJsonSerializer data = new DataContractJsonSerializer(typeof(Dictionary<string, string>));

                data.WriteObject(file, list);
            }
        }
        /// <summary>
        /// 读取Json集合返回一个List集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static List<T> Read<T>(string path)
        {
            //判断有没有此文件
            if (!File.Exists(path))
            {
                return null;
            }
            using (FileStream file = new FileStream(path, FileMode.OpenOrCreate))
            {
                DataContractJsonSerializer data = new DataContractJsonSerializer(typeof(List<T>));
                file.Seek(0, SeekOrigin.Begin);
                try
                {
                    return (List<T>)data.ReadObject(file);
                }
                catch { return null; }
            }
        }
        /// <summary>
        /// 序列化字典类
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Dictionary<string, string> Read(string path)
        {
            //判断有没有此文件
            if (!File.Exists(path))
            {
                return null;
            }
            using (FileStream file = new FileStream(path, FileMode.OpenOrCreate))
            {
                DataContractJsonSerializer data = new DataContractJsonSerializer(typeof(Dictionary<string, string>));
                file.Seek(0, SeekOrigin.Begin);
                try
                {
                    return (Dictionary<string, string>)data.ReadObject(file);
                }
                catch { return null; }
            }
        }
    }
}
